package com.cqq.print.business.controller.order;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.cqq.auth.service.UserService;
import com.cqq.auth.service.bean.UserBean;
import com.cqq.auth.service.bean.UserQueryBean;
import com.cqq.base.filter.FMContext;
import com.cqq.common.core.base.BaseController;
import com.cqq.common.core.bean.PageInfoBean;
import com.cqq.print.base.service.PBookCategoryService;
import com.cqq.print.base.service.bean.PBookCategoryBean;
import com.cqq.print.business.controller.view.PBATView;
import com.cqq.print.business.service.PArticleService;
import com.cqq.print.business.service.PBookService;
import com.cqq.print.business.service.POrderDetailService;
import com.cqq.print.business.service.POrderService;
import com.cqq.print.business.service.PTitleService;
import com.cqq.print.business.service.bean.PArticleBean;
import com.cqq.print.business.service.bean.PBookBean;
import com.cqq.print.business.service.bean.POrderBean;
import com.cqq.print.business.service.bean.POrderDetailBean;
import com.cqq.print.business.service.bean.PTitleBean;
import com.cqq.print.constant.Constant;
import com.cqq.pro.util.DateUtil;
import com.cqq.pro.util.OrderNuMUitl;
import com.cqq.pro.util.PropertiesUtil;
import com.cqq.pro.util.ResponseUtil;

/**
 * 2015/06/25
 *
 * @author chenqq
 */
@Controller(value = "orderController")
@RequestMapping(value = { "ordermanage" }, method = {
		RequestMethod.POST,
		RequestMethod.GET })
public class OrderController extends BaseController{
	
	@Autowired
	private POrderService pOrderService;
	@Autowired
	private POrderDetailService pOrderDetailService;
	@Autowired
	private PBookCategoryService pBookCategoryService;
	@Autowired
	private UserService userService;
	@Autowired
	private PBookService pBookService;
	@Autowired
	private PArticleService pArticleService;
	@Autowired
	private PTitleService pTitleService;

	@RequestMapping(value = { "list" }, method = {
			RequestMethod.GET,
			RequestMethod.POST })
	public String toList(HttpServletRequest request, ModelMap out) {

		return "order/ordermanager";
		
	}
	
	@RequestMapping("listAjax")
	public String toListAjax(HttpServletRequest request, ModelMap out) throws UnsupportedEncodingException {
		String name = request.getParameter("name");		
		String pubSimpleName = request.getParameter("pubSimpleName");		
		String contactName = request.getParameter("contactName");
		String status = request.getParameter("status");
		String checkStatus = request.getParameter("checkStatus");
		String currentPage = request.getParameter("currentPage");
		String pageSize = request.getParameter("pageSize");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		Map<String,Object> map = new HashMap<String, Object>();
		
		if(name!=null&&!name.trim().equals("")){
			name = URLDecoder.decode(name, "utf-8");
			map.put("name", name);
		}
		if(pubSimpleName!=null&&!pubSimpleName.trim().equals("")){
			pubSimpleName = URLDecoder.decode(pubSimpleName, "utf-8");
			map.put("pubSimpleName", pubSimpleName);
		}
		if(contactName!=null&&!contactName.trim().equals("")){
			contactName = URLDecoder.decode(contactName, "utf-8");
			map.put("contactName", contactName);
		}
		if(status!=null&&status.trim().length()>0&&Integer.parseInt(status)>=0){
			map.put("status",Integer.parseInt(status));
		}
		if(checkStatus!=null&&checkStatus.trim().length()>0&&Integer.parseInt(checkStatus)>=0){
			map.put("checkStatus",Integer.parseInt(checkStatus));
		}
		if(currentPage==null||currentPage.trim().length()<1){
			currentPage = "1";
		}
		if(pageSize==null||pageSize.trim().length()<1){
			pageSize = "20";
		}
		
		if(startDate==null||StringUtils.isEmpty(startDate))
		    startDate = DateUtil.formatDate(DateUtil.getFirstDateOfCurrentMonth());
		if(endDate==null||StringUtils.isEmpty(endDate))
			endDate = DateUtil.getCurrDateAfterAddDays(1);
		else
			endDate = DateUtil.addDaysForDate(endDate,1);
		
		map.put("startDate", startDate+" 00:00:00");
		map.put("endDate", endDate+" 00:00:00");
		
		int offset = (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize);
		map.put("orderClause", "po.create_date desc");
		map.put("pageSize", Integer.parseInt(pageSize));
		map.put("offset", offset);
		
		PageInfoBean<POrderBean> page = pOrderService.queryPageOrders(map);
		page.setPageNo(Integer.parseInt(currentPage));
		page.setPageSize(Integer.parseInt(pageSize));
		out.put("page", page);
		
		
		return "order/ordermanager";
	}
	
	@RequestMapping("toAddOrder")
	public String toAddOrder(HttpServletRequest request, ModelMap out) throws UnsupportedEncodingException {
		//图书类型
		List<PBookCategoryBean> listPBBean = pBookCategoryService.queryBookCateGory();
		
		//加载订单号
		String name = PropertiesUtil.getConfigValue("print.order.name");
		String dateFormate = PropertiesUtil.getConfigValue("print.order.dateformate");
		int numLength = Integer.parseInt(PropertiesUtil.getConfigValue("print.order.num.length"));
		String currDate = DateUtil.formatDate(System.currentTimeMillis());
		Map<String,Object> map = pOrderService.getMaxOrderNumToDay(currDate);
		String maxOrderNum =""; 
		if(map!=null&&map.get("ordernum")!=null)
			maxOrderNum = map.get("ordernum").toString();
		String orderNum = OrderNuMUitl.getNewTaskNum(maxOrderNum,name,dateFormate,numLength);
		
		int roleId = Integer.parseInt(PropertiesUtil.getConfigValue("print.order.foreman.roleId"));
		UserQueryBean queryBean = new UserQueryBean();
		queryBean.setRoleId(roleId);
		queryBean.setNeedPaging(false);
		PageInfoBean<UserBean> page = userService.queryUserByPage(queryBean);
		
		out.put("listPBBean",listPBBean);
		out.put("listUser",page.getData());
		out.put("orderNum", orderNum);
		return "order/addPOrder";
	}
	
	@RequestMapping("submitPOrder")
	public void submitPOrder(POrderBean pOrderBean,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		//订单信息
		JSONObject json = new JSONObject();
		try{
			pOrderBean.setEndTime(DateUtil.formateStrToTDate(pOrderBean.getEndDate()));
			pOrderBean.setStartTime(DateUtil.formateStrToTDate(pOrderBean.getStartDate()));
			Date currDate = new Date();
			pOrderBean.setUpdateDate(currDate);
			pOrderBean.setCreateDate(currDate);
			pOrderBean.setCreateId(FMContext.getCurrent().getUserId());
			int orderId = pOrderService.insertSelective(pOrderBean);
			json.put("result", "success");
			json.put("orderId", orderId);
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("toAddOrderDetail")
	public String toAddOrderDetail(HttpServletRequest request, ModelMap out) throws UnsupportedEncodingException {
		String id = request.getParameter("orderId");
		if(id==null||id.trim().length()<=0){
			id = "0";
		}
		//订单信息
		POrderBean orderBean = pOrderService.queryOrderById(Integer.parseInt(id));
		//订单明细信息
		List<POrderDetailBean> listDetailBean = pOrderDetailService.queryDetailsByOrderId(Integer.parseInt(id));
		orderBean.setDetailCount(listDetailBean!=null?listDetailBean.size():0);
		//图书类型
		List<PBookCategoryBean> listPBBean = pBookCategoryService.queryBookCateGory();
		
		//版面-开本
		PBookBean bookBean = pBookService.selectByPrimaryKey(orderBean.getpBookId());
		//版面-正文
		PArticleBean articleBean = pArticleService.selectByPrimaryKey(orderBean.getpArticleId());
		//版面-标题
		PTitleBean titleBean = pTitleService.selectByPrimaryKey(orderBean.getpTitleId());
		
		out.put("bookBean",bookBean);
		out.put("articleBean",articleBean);
		out.put("titleBean",titleBean);
		out.put("listPBBean",listPBBean);
		out.put("listDetailBean",listDetailBean);
		out.put("orderBean",orderBean);
		return "order/addPOrderDetail";
	}
	
	@RequestMapping("submitPOrderDetail")
	public void submitPOrderDetail(POrderDetailBean pOrderDetailBean, HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		//订单信息
		JSONObject json = new JSONObject();
		try{

			pOrderDetailService.insertSelective(pOrderDetailBean);
			
			json.put("result", "success");
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("toEditOrder")
	public String toEditOrder(HttpServletRequest request, ModelMap out) throws UnsupportedEncodingException {
		String id = request.getParameter("orderId");
		if(id==null||id.trim().length()<=0){
			id = "0";
		}
		POrderBean orderBean = pOrderService.queryOrderById(Integer.parseInt(id));
		//图书类型
		List<PBookCategoryBean> listPBBean = pBookCategoryService.queryBookCateGory();
		out.put("listPBBean",listPBBean);
		out.put("orderBean",orderBean);
		return "order/editPOrder";
	}
	
	@RequestMapping("savePOrder")
	public void savePOrder(POrderBean pOrderBean,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		//订单信息
		JSONObject json = new JSONObject();
		try{
			Date currDate = new Date();
			pOrderBean.setUpdateDate(currDate);
			pOrderService.updateOrder(pOrderBean);
			json.put("result", "success");
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("toEditOrderDetail")
	public String toEditOrderDetail(String orderId, ModelMap out) throws UnsupportedEncodingException {

		return "order/editPOrderDetail";
	}
	
	@RequestMapping("getPOrderDetail")
	public void getPOrderDetail(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		JSONObject json =  new JSONObject();
		String id = request.getParameter("orderId");
		if(id!=null&&id.trim().length()>0){
			try{				
				POrderBean pOrderBean = pOrderService.queryOrderAndDetailById(Integer.parseInt(id));
				json.put("result", "success");
				json.put("pOrderBean", pOrderBean);
			}catch(Exception e){
				json.put("msg", "程序异常，请联系运维人员!");
				log.error(e.getMessage());
			}
		}else{
			json.put("result", "faild");
			json.put("msg", "orderId is null");
		}
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("updateCheckStatus")
	public void updateCheckStatus(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		JSONObject json =  new JSONObject();
		String id = request.getParameter("orderId");
		if(id!=null&&id.trim().length()>0){
			try{				
				POrderBean pOrderBean = new POrderBean();
				pOrderBean.setId(Integer.parseInt(id));
				pOrderBean.setCheckStatus(Constant.ORDER_CHECKSTATUS_DONE);
				pOrderService.updateCheckStatus(pOrderBean);
				json.put("result", "success");
			}catch(Exception e){
				json.put("msg", "程序异常，请联系运维人员!");
				log.error(e.getMessage());
			}
		}else{
			json.put("result", "faild");
			json.put("msg", "orderId is null");
		}
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("updateFlowStatus")
	public void updateFlowStatus(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		JSONObject json =  new JSONObject();
		String id = request.getParameter("orderId");
		if(id!=null&&id.trim().length()>0){
			try{				
				POrderBean pOrderBean = new POrderBean();
				pOrderBean.setId(Integer.parseInt(id));
				pOrderBean.setCheckStatus(Constant.ORDER_FLOWSTATUS_DONE);
				pOrderService.updateCheckStatus(pOrderBean);
				json.put("result", "success");
			}catch(Exception e){
				json.put("msg", "程序异常，请联系运维人员!");
				log.error(e.getMessage());
			}
		}else{
			json.put("result", "faild");
			json.put("msg", "orderId is null");
		}
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("updateStatus")
	public void updateStatus(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		JSONObject json =  new JSONObject();
		String id = request.getParameter("orderId");
		if(id!=null&&id.trim().length()>0){
			try{				
				POrderBean pOrderBean = new POrderBean();
				pOrderBean.setId(Integer.parseInt(id));
				//pOrderBean.setCheckStatus(Constant.ORDER_STATUS_DONE);
				pOrderService.updateCheckStatus(pOrderBean);
				json.put("result", "success");
			}catch(Exception e){
				json.put("msg", "程序异常，请联系运维人员!");
				log.error(e.getMessage());
			}
		}else{
			json.put("result", "faild");
			json.put("msg", "orderId is null");
		}
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("deleteOrderDetail")
	public void deleteOrderDetail(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		JSONObject json =  new JSONObject();
		String id = request.getParameter("orderDetailId");
		if(id!=null&&id.trim().length()>0){
			try{				
				pOrderDetailService.deleteDetailById(Integer.parseInt(id));
				json.put("result", "success");
			}catch(Exception e){
				json.put("msg", "程序异常，请联系运维人员!");
				log.error(e.getMessage());
			}
		}else{
			json.put("result", "faild");
			json.put("msg", "orderDetailId is null");
		}
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("toAddPBAT")
	public String toAddPBAT(int orderId, ModelMap out) throws UnsupportedEncodingException {
		//订单信息
		POrderBean orderBean = pOrderService.queryOrderById(orderId);
		//版面-开本
		PBookBean bookBean = pBookService.selectByPrimaryKey(orderBean.getpBookId());
		//版面-正文
		PArticleBean articleBean = pArticleService.selectByPrimaryKey(orderBean.getpArticleId());
		//版面-标题
		PTitleBean titleBean = pTitleService.selectByPrimaryKey(orderBean.getpTitleId());
		
		out.put("orderBean", orderBean);
		out.put("bookBean", bookBean);
		out.put("articleBean", articleBean);
		out.put("titleBean", titleBean);
		return "order/addPbat-index";
	}
	
	@RequestMapping("savePbat")
	public void savePbat(PBATView pbatView,HttpServletResponse response){
		//版面信息
		JSONObject json = new JSONObject();
		try{
			PBookBean book = new PBookBean();
			PArticleBean article = new PArticleBean();
			PTitleBean title = new PTitleBean();
			BeanUtils.copyProperties(pbatView, book);
			BeanUtils.copyProperties(pbatView, article);
			BeanUtils.copyProperties(pbatView, title);
			Integer pBookId = pbatView.getpBookId();
			Integer pArticleId = pbatView.getpArticleId();
			Integer pTitleId = pbatView.getpTitleId();
			if(pBookId==null||pBookId<=0){
				pBookId = pBookService.insertSelective(book);
			}else{
				book.setId(pBookId);
				pBookService.updateByPrimaryKeySelective(book);
			}
			if(pArticleId==null||pArticleId<=0){
				pArticleId= pArticleService.insertSelective(article);
			}else{
				article.setId(pArticleId);
				pArticleService.updateByPrimaryKeySelective(article);
			}
			if(pTitleId==null||pTitleId<=0){
				pTitleId = pTitleService.insertSelective(title);
			}else{
				title.setId(pTitleId);
				pTitleService.updateByPrimaryKeySelective(title);
			}
			
			POrderBean orderBean = new POrderBean();
			orderBean.setId(pbatView.getOrderId());
			orderBean.setpBookId(pBookId);
			orderBean.setpArticleId(pArticleId);
			orderBean.setpTitleId(pTitleId);
			pOrderService.updateOrder(orderBean);
			json.put("result", "success");
			json.put("orderId", pbatView.getOrderId());
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
}
